package cn.cdu.medical.controller;

import cn.cdu.basics.baseVo.Result;
import cn.cdu.basics.utils.ResultUtil;
import cn.cdu.basics.utils.SecurityUtil;
import cn.cdu.medical.entity.ChatMessage;
import cn.cdu.medical.dto.ConsultationIdWithTime;
import cn.cdu.medical.service.ChatMessageService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(tags = "问诊聊天记录接口")
@RequestMapping("/zwz")
public class ChatMessageController {
    
    private static final Logger log = LoggerFactory.getLogger(ChatMessageController.class);

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private SecurityUtil securityUtil;

    @GetMapping("/messages/{consultationId}")
    public Result<List<ChatMessage>> getMessages(@PathVariable String consultationId) {
        try {
            List<ChatMessage> messages = chatMessageService.getMessagesByConsultationId(consultationId);
            return new ResultUtil<List<ChatMessage>>().setData(messages);
        } catch (Exception e) {
            log.error("Failed to get messages for consultation {}: {}", consultationId, e.getMessage());
            return new ResultUtil<List<ChatMessage>>().setErrorMsg("获取聊天记录失败：" + e.getMessage());
        }
    }

    @GetMapping("/all-consultations")
    public Result<Map<String, List<Map<String, Object>>>> getAllConsultations() {
        try {
            String userId = securityUtil.getCurrUser().getId();
            Map<String, List<ChatMessage>> consultations = chatMessageService.getAllUserConsultations(userId);
            Map<String, List<Map<String, Object>>> safeConsultations = new HashMap<>();
            for (Map.Entry<String, List<ChatMessage>> entry : consultations.entrySet()) {
                List<Map<String, Object>> safeList = entry.getValue().stream().map(msg -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", msg.getId());
                    map.put("consultationId", msg.getConsultationId());
                    map.put("userId", msg.getUserId());
                    map.put("content", msg.getContent() == null ? "" : msg.getContent());
                    map.put("type", msg.getType());
                    map.put("createTime", msg.getCreateTime());
                    return map;
                }).collect(Collectors.toList());
                safeConsultations.put(entry.getKey(), safeList);
            }
            return new ResultUtil<Map<String, List<Map<String, Object>>>>().setData(safeConsultations);
        } catch (Exception e) {
            return new ResultUtil<Map<String, List<Map<String, Object>>>>().setErrorMsg("获取咨询记录失败：" + e.getMessage());
        }
    }

    @GetMapping("/recent-consultations")
    public Result<List<String>> getRecentConsultations() {
        try {
            String userId = null;
            try {
                userId = securityUtil.getCurrUser().getId();
            } catch (Exception e) {
                log.warn("User not logged in: {}", e.getMessage());
                return new ResultUtil<List<String>>().setData(new ArrayList<>());
            }
            
            if (userId == null) {
                return new ResultUtil<List<String>>().setData(new ArrayList<>());
            }
            
            // 默认获取最近10条记录
            List<ConsultationIdWithTime> consultations = chatMessageService.getRecentConsultationIds(userId, 10);
            List<String> consultationIds = consultations.stream()
                .map(ConsultationIdWithTime::getConsultationId)
                .collect(Collectors.toList());
            return new ResultUtil<List<String>>().setData(consultationIds);
        } catch (Exception e) {
            log.error("Failed to get recent consultations: {}", e.getMessage());
            return new ResultUtil<List<String>>().setErrorMsg("获取最近咨询记录失败：" + e.getMessage());
        }
    }
} 